<template>
	<div class="adminManage">
		<div class="public-search-box">
			<el-form inline
					 ref="searchRef"
					 :model="searchData">
				<el-form-item>
					<el-input v-model="searchData.username"
							  size="small"
							  clearable
							  placeholder="用户名"
							  @input="pageChange(1)">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="searchData.nickname"
							  size="small"
							  clearable
							  placeholder="昵称"
							  @input="pageChange(1)">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"
							   size="small"
							   icon="el-icon-search"
							   v-if="hasPerm('admin:list')"
							   @click="pageChange(1)">查询
					</el-button>
					<el-button type="primary"
							   size="small"
							   icon="el-icon-plus"
							   v-if="hasPerm('admin:add')"
							   @click="addOrUpdate('add')">新增
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="public-table"
			 v-loading="loading"
			 element-loading-text="拼命加载中...">
			<el-table :data="list"
					  height="calc(100vh - 114px - 30px - 61px - 72px - 30px)"
					  style="width: 100%;">
				<el-table-column prop="orderNumber"
								 label="序号"
								 align="center"></el-table-column>
				<el-table-column prop="username"
								 label="用户名"
								 align="center"></el-table-column>
				<el-table-column prop="nickname"
								 label="昵称"
								 align="center"></el-table-column>
				<el-table-column prop="phone"
								 label="手机号"
								 align="center"></el-table-column>
				<el-table-column prop="email"
								 label="邮箱"
								 align="center"></el-table-column>
				<el-table-column prop="created_time"
								 label="注册时间"
								 align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.created_time | dateTime }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="updated_time"
								 label="更新时间"
								 align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.updated_time | dateTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作"
								 align="center">
					<template slot-scope="scope">
						<el-button type="primary"
								   size="small"
								   v-if="hasPerm('admin:edit')"
								   @click="addOrUpdate('update', scope.row)">修改
						</el-button>
						<el-button type="danger"
								   size="small"
								   v-if="hasPerm('admin:delete')"
								   @click="del(scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination :total="total"
					:page="searchData.currentPage"
					:pageSize="searchData.pageSize"
					@pageChange="pageChange">
		</pagination>
		<el-dialog :title="saveData.id === '' ? '新增' : '修改'"
				   width="500px"
				   :close-on-click-modal="false"
				   :visible.sync="addOrUpdateVisible"
				   custom-class="public-dialog"
				   :before-close="close">
			<el-form ref="addOrUpdateRef"
					 :model="saveData"
					 :rules="addOrUpdateRules"
					 label-width="100px">
				<el-form-item label="用户名:"
							  prop="username">
					<el-input v-model="saveData.username"></el-input>
				</el-form-item>
				<el-form-item v-if="passShow"
							  label="密码:"
							  prop="password">
					<el-input v-model="saveData.password"
							  type="password"></el-input>
				</el-form-item>
				<el-form-item v-if="passShow"
							  label="确认密码:"
							  prop="comfirmPassword">
					<el-input v-model="saveData.comfirmPassword"
							  type="password"></el-input>
				</el-form-item>
				<el-form-item label="昵称:"
							  prop="nickname">
					<el-input v-model="saveData.nickname"></el-input>
				</el-form-item>
				<el-form-item label="角色:"
							  prop="role">
					<el-select v-model="saveData.role"
							   placeholder="请选择角色">
						<el-option v-for="item in roleList"
								   :key="item.id"
								   :label="item.name"
								   :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="手机号:"
							  prop="phone">
					<el-input v-model="saveData.phone"></el-input>
				</el-form-item>
				<el-form-item label="邮箱:"
							  prop="email">
					<el-input v-model="saveData.email"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer">
                <el-button size="small"
						   @click="close">取消</el-button>
                <el-button type="primary"
						   size="small"
						   @click="submit">保存</el-button>
            </span>
		</el-dialog>
	</div>
</template>

<script>
import pagination from '@/components/pagination/pagination'
import { adminApi, roleApi } from '@/api'
import { numSort, debounce } from '@/utils'

export default {
	name: 'admin',
	data () {
		let validatePass = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'))
			} else if (value !== this.saveData.password) {
				callback(new Error('两次输入密码不一致!'))
			} else {
				callback()
			}
		}
		return {
			loading: true,
			searchData: {
				username: '',
				nickname: '',
				currentPage: 1,
				pageSize: 10
			},
			total: 0,
			list: [],
			addOrUpdateVisible: false,
			passShow: true, // 是否显示密码框
			saveData: {
				id: '',
				username: '',
				password: '',
				comfirmPassword: '',
				nickname: '',
				phone: '',
				email: '',
				role: -1
			},
			addOrUpdateRules: {
				username: [
					{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					}
				],
				nickname: [
					{ required: true, message: '请输入昵称', trigger: 'blur' }
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' }
				],
				comfirmPassword: [
					{
						required: true,
						validator: validatePass,
						trigger: 'blur'
					}
				],
				phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: 'blur'
					}
				],
				email: [
					{ required: true, message: '请输入邮箱', trigger: 'blur' }
				]
			},
			roleList: []
		}
	},
	mounted () {
		this.getList()
	},
	methods: {
		// 获取列表
		async getList () {
			this.loading = true
			let params = Object.assign({}, this.searchData)
			const { err, data } = await adminApi.getPage(params)
			if (err) {
				return false
			}
			if (data.list.length === 0 && params.currentPage !== 1) {
				// 删除后判断当前页面是否无数据 如果有数据则正常处理数据，如不正常数据为空时。则重新获取有数据的页面条件
				// 删除后当前页面无数据时，则重新计算有数据的页面重新获取数据
				let current = Math.ceil(data.totalCount / params.pageSize)
				this.pageChange(current)
			} else {
				data.list.forEach((item, index) => {
					item['orderNumber'] = numSort(
						index,
						params.currentPage,
						params.pageSize
					)
				})
				this.list = data.list
				this.total = data.totalCount
				this.loading = false
			}
		},
		async getRoleList () {
			const { err, data } = await roleApi.getList()
			this.roleList = data
		},
		addOrUpdate (val, item) {
			this.addOrUpdateVisible = true
			this.getRoleList()
			if (val === 'add') {
				this.passShow = true
			} else if (val === 'update') {
				this.passShow = false
				this.getDetail(item)
			}
		},
		// 提交
		submit: debounce(function () {
			let api = null
			let message = ''
			this.$refs.addOrUpdateRef.validate(async (valid) => {
				if (valid) {
					let params = Object.assign({}, this.saveData)
					if (params.id === '') {
						api = adminApi.addData
						message = '添加成功'
					} else {
						api = adminApi.updateData
						message = '更新成功'
					}
					const { err, data } = await api(params)
					if (err) {
						return false
					}
					this.$message({
						message: message,
						type: 'success'
					})
					this.close()
					this.getList()
				}
			})
		}, 1000),
		// 获取详情
		async getDetail (item) {
			const { err, data } = await adminApi.detailData(item.id)
			if (err) {
				return false
			}
			this.saveData.id = data.id
			this.saveData.username = data.username
			this.saveData.nickname = data.nickname
			this.saveData.phone = data.phone
			this.saveData.email = data.email
			this.saveData.role = data.role
		},
		// 删除
		del (item) {
			this.$confirm('确定删除当前数据吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const { err, data } = await adminApi.delData(item)
				if (err) {
					return false
				}
				this.$message({
					message: '删除成功',
					type: 'success'
				})
				this.getList()
			}).catch(() => {})
		},
		// 分页
		pageChange (val, limit) {
			if (limit) {
				this.searchData.pageSize = limit
			}
			this.searchData.currentPage = val
			this.getList()
		},
		// 关闭
		close () {
			this.addOrUpdateVisible = false
			this.saveData.id = ''
			this.$refs.addOrUpdateRef.resetFields()
		}
	},
	components: {
		pagination
	}
}
</script>

<style scoped lang="less">
.adminManage {
	width: 100%;
}
</style>
